# -*- coding:utf-8 -*-#
# -------------------------------------------------------------------------
# ProjectName:       zhcx-service-test
# FileName:          brand_activity_allocationOfAdvertising.py
# Author:            xun
# Date:              2024/7/26 14:41
# Description:
# --------------------------------------------------------------------------

from common_methods import sent_request,DuSql,create_log,more_tool,defult_date
from datetime import date,timedelta,datetime

dm = DuSql()
s = sent_request()
log = create_log()
mt = more_tool()

class Allocation_of_advertising:

    def deal_advertising_fee_plus(self,check_date=None):
        '''先进行合计值对比'''
        # 先处理从接口获取的广告费
        if not check_date:
            check_date = str(defult_date()[0]).replace('-','')
        #将从接口获取的广告费替换成{活动id:广告费}
        request_fee = s.get_advertising_fee(mt.data_conversion(dm.get_all_OrderSourceId(check_date)),check_date)
        request_data={}
        for i in request_fee:
            request_data[i['CampaignId']]=i['Cost']

        #处理从fee表查到各个活动的广告费
        database_fee = ''
        for i in list(request_data.keys()):
            database_fee += str(i)
            if i != list(request_data.keys())[-1]:
                database_fee += "\',\'"
        database_fee = mt.datas_conversion(dm.get_all_advertising_fee(database_fee, defult_date()),ifdict=1)

        ckeck_result = ''
        for i,k in database_fee.items():
           # print(type(i))
           # print(type(list(request_data.keys())[0]))
           # break
            key = int(i)
            if k != request_data[int(key)]:
                print('活动ID为：{0}在接口获取的广告费为:{1},在数据库查询的广告费为：{2},差异为:{3}'.format(i,request_data[i],k,float(request_data[i]))-k)

    def deal_advertising_fee(self):
        #先查出各个活动包含的Asin
        get_Initial_data = s.get_advertising_fee(mt.data_conversion(dm.get_all_youpinOrderSourceId()),defult_date()[0])
        get_Initial_dict = {}
        for i in get_Initial_data:
            list2 = []
            list2.append(i['OrderSourceCountry'])
            list2.append(i['Cost'])
            get_Initial_dict[str(i["CampaignId"])] = list2 #原始数据,活动:[国家,金额]

        #查出各个活动包含的Asin
        get_Campaign_Asin = {}
        for  i in list(get_Initial_dict.keys()):
            get_Asin = s.get_Campaign_Asin(i)
            list3 = []
            for j in get_Asin['Asins']:
                j += '_'+get_Initial_dict[i][0]
                list3.append(j)
            get_Campaign_Asin[str(i)] = list3 #活动id:[所有Asin_国家]

        #判断各个活动中Asin在上月是否存在出单量
        get_Share_OrderNumber = {}
        for i in dm.get_OrderNumber():
            country_asin = i[1]+'_'+i[0]
            get_Share_OrderNumber[country_asin]=i[2] # 国家+Asin:单量
        Related_Asin_proportion = {}
        for RelatedID,Asin in get_Campaign_Asin.items():
            Related_OrderNum = 0
            Asin_dict = {}
            for i in Asin:
                if i in get_Share_OrderNumber.keys():
                    Related_OrderNum += get_Share_OrderNumber[i]    #算出活动的合计单量
                    Asin_dict[i] = get_Share_OrderNumber[i]     #算出每个asin的单量
                else:
                    Asin_dict[i] = 0
            asin_num = {}
            if Related_OrderNum:
                for asin in Asin:
                    if Asin_dict[asin]:
                        asin_num[asin[:-3]] = Asin_dict[asin]/Related_OrderNum
                    else:
                        asin_num[asin] = 0
            else:
                for asin in Asin:
                    asin_num[asin[:-3]] = 1/len(Asin)
            Related_Asin_proportion[RelatedID] = asin_num
        return get_Initial_dict,Related_Asin_proportion # 活动:[国家,金额] , 活动:{Asin:分摊比例}

    def check_advertising_fee(self):
        get_Initial_dict, Related_Asin_proportion = self.deal_advertising_fee()
        get_all_advertising_fee=mt.data_conversion_dict(dm.get_all_advertising_fee(defult_date()[0])) #活动:金额
        get_all_asin_fee = mt.datas_conversion_dict(dm.get_all_asin_fee(defult_date()[0])) # 活动:{asin:金额}
        Related_total,Asin_total = 0,0
        send_dingding_totallog,send_dingding_log = '',''
        for RelatedID,list in get_Initial_dict.items():
            Related_total +=1
            get_proportion = Related_Asin_proportion[RelatedID] #获得活动中的所有Asin及分摊比例
            if RelatedID in get_all_advertising_fee.keys():
                if list[-1] == get_all_advertising_fee[RelatedID]:
                    num = 0
                    for asin,ratio in get_proportion.items():
                        Asin_total += 1
                        amount = get_all_advertising_fee[RelatedID]*ratio
                        if asin in get_all_asin_fee[RelatedID].keys():
                            get_sql_amount = get_all_asin_fee[RelatedID][asin]
                            if round(amount,4) == round(get_sql_amount,4):
                                continue
                            else:
                                num+=1
                        else:
                            if amount:
                                send_dingding_log += "分摊有误,有误活动为 {0},Asin为 {1}".format(RelatedID,asin)
                                send_dingding_log += '\n'
                                print("分摊有误,有误活动为 {0},Asin为 {1}".format(RelatedID,asin))
                    if num > 2:
                        #这里做两步操作,如果分摊后的结果等于活动总广告费,则算分摊正确,反之则不正确,打印分摊结果差异最大的Asin和活动
                        if list[-1] == round(sum(get_all_asin_fee[RelatedID].values()),2):
                            continue
                        else:
                            send_dingding_log += "活动{0}分摊结果有误,有误的Asin有{1},实际活动金额:{2},分摊后合计总金额为：{3}".format(RelatedID,get_all_asin_fee[RelatedID].values(),list[-1],sum(get_all_asin_fee[RelatedID].values()))
                            send_dingding_log += '\n'
                            print("活动{0}分摊结果有误,有误的Asin有{1},实际活动金额:{2},分摊后合计总金额为：{3}".format(RelatedID,get_all_asin_fee[RelatedID].values(),list[-1],sum(get_all_asin_fee[RelatedID].values())))
                else:
                    send_dingding_totallog += '{0}活动ID为：{1}, SB广告费有误,实际广告费为{2},而数据库中为{3}'.format(defult_date()[0],RelatedID,list[-1],get_all_advertising_fee[RelatedID])
                    send_dingding_totallog += '\n'
                    print('{0}活动ID为：{1}, SB广告费有误,实际广告费为{2},而数据库中为{3}'.format(defult_date()[0],RelatedID,list[-1],get_all_advertising_fee[RelatedID]))
        if send_dingding_totallog:
            s.send_dingding_message("查询{0}品牌活动广告费的分摊数据,活动共{1}条,查验Asin {2}个;\n"
                                    "存在以下广告活动总广告费同步有误: \n{3}".format(defult_date()[0],Related_total, Asin_total,
                                                                                 send_dingding_totallog))
        elif send_dingding_log:
            s.send_dingding_message("查询{0}品牌活动广告费的分摊数据,活动共{1}条,查验Asin {2}个;\n"
                                    "所有活动总广告费都同步正确\n 存在以下广告活动分摊有误: \n{3}".format(defult_date()[0],Related_total,Asin_total,send_dingding_log))
        else:
            s.send_dingding_message('查询{0}品牌活动广告费的分摊数据,活动共{1}条,查验Asin {2}个;暂无分摊有误数据'.format(defult_date()[0],Related_total,Asin_total))

    def close(self):
        dm.cousor.close()
        dm.connect.close()
        s.s.close()
    #记得加一个关闭数据库、接口的操作

    def test_run(self):
        self.check_advertising_fee()
        self.close()

if __name__ == '__main__':
    Allocation_of_advertising().test_run()